from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import *
from rest_framework_jwt.utils import jwt_encode_handler
from celery_tasks.sms_code.tasks import send_message
import json
import redis
import random
import re
import time
from django.utils import timezone
from users.ser import *
from django.db import connection
from django.db.models import Count


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        phone = request.data.get('phone')
        password = request.data.get('password')
        smscode = request.data.get('smsCode')
        if not all([username, phone, password, smscode]):
            return Response({
                'msg': '信息不完善',
                'code': 400
            })
        user = User.objects.filter(username=username)
        res = redis.Redis(host='127.0.0.1', port=6379, db=3)
        scode = res.get('sms_%s' % phone)
        date = time.strftime('%y-%m-%d')
        print(user)
        if not user:
                try:
                    if str(scode.decode()) == str(smscode):
                        user_info = User.objects.create(username=username, password=password, phone=phone, email='aaa@qq.com')
                        """生成token"""
                        payload = {
                            'user': user_info.username
                        }
                        token = jwt_encode_handler(payload)
                        print(token)
                    else:
                        return Response({
                            'msg': '1验证码有误',
                            'code': 400
                        })
                except Exception as e:
                    print(e)
                    return Response({
                        'msg': '1登录失败',
                        'code': 400
                    })
                user_info.last_login = timezone.now()
                return Response({
                    'msg': '1登录成功',
                    'code': 200,
                    'user': user_info.username,
                    'token':token
                })
        else:
            try:
                user = User.objects.get(username=username)
                if user.password == str(password) and str(scode.decode()) == str(smscode):
                    """生成token"""
                    payload = {
                        'user': user.username
                    }
                    token = jwt_encode_handler(payload)
                    print(token)
                    user.last_login = timezone.now()
                    user.save()
                    print(timezone.now())
                    return Response({
                        'msg': '2登录成功',
                        'code': 200,
                        'user': user.username,
                        'token': token
                    })
                else:
                    return Response({
                        'msg': '输入的密码或验证码有误',
                        'code': 400
                    })
            except Exception as e:
                print(e)
                return Response({
                    'msg': '2登录失败',
                    'code': 400
                })


class SmsCode(APIView):
    def get(self, request, mobile):
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return Response({
                    'msg': '手机号格式错误',
                    'code': 400
                })
        data = random.randint(000000, 999999)
        if mobile:
            resp = send_message.delay(mobile, data)
            if resp:
                res = redis.Redis(host='127.0.0.1', port=6379, db=3)
                res.set('sms_%s' % mobile, data, ex=60)
                mcode = res.get('sms_%s' % mobile)
                return Response({
                    'msg': '发送成功',
                    'code': 200,
                    'smscode': mcode
                })
            else:
                return Response({
                    'msg': '发送失败',
                    'code': 500,
                })
        else:
            return Response({
                'msg': '参数错误',
                'code': 400,
            })


class UsersCountView(APIView):
    def get(self, request):
        # 获取用户总人数
        num = User.objects.all().count()
        return Response({'total_count': num})


class DaliAddUserView(APIView):
    def get(self, request):
        # 日增加用户数
        # 获取当前的时间
        date = time.strftime("%y-%m-%d")  # 如"22-03-30"
        # 根据当前时间过滤用户，获取用户数量
        num = User.objects.filter(create_time__contains=date).count()
        # 返回
        return Response({"total_count": num})


class DalyLiveUserView(APIView):
    def get(self, request):
        # 日活跃用户
        date = time.strftime("%y-%m-%d")
        # 根据当前时间过滤用户，获取用户数量
        num = User.objects.filter(last_login__contains=date).count()
        # 返回
        return Response({"total_count": num})


from django.core.paginator import Paginator
from users.utils import *
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListCreateAPIView


class GetData(ListCreateAPIView):
    # def get(self, request):
    #     pagination_class = MyPagination
    #     try:
    #         user = User.objects.all()
    #     except Exception as e:
    #         print(e)
    #         return Response({
    #             'code': 400,
    #             'msg': '获取用户失败'
    #         })
    #     ser = UserSer(user, many=True)
    #     return Response({
    #         'code': 200,
    #         'msg': '获取用户成功',
    #         'aUserList': ser.data
    #     })
    #
    queryset = User.objects.all()
    serializer_class = UserSer
    pagination_class = MyPagination


class AddData(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        try:
            User.objects.create(username=username, password=password, phone=phone, email=email)
        except Exception as e:
            print(e)
            return Response({
                'code': 400,
                'msg': '添加用户失败'
            })
        return Response({
            'code': 200,
            'msg': '添加用户成功'
        })


class DelUser(APIView):
    def get(self, request, id):
        try:
            user = User.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({
                'code': 400,
                'msg': '获取用户失败'
            })
        return Response({
            'code': 200,
            'msg': '获取用户成功',
            'username': user.username,
            'password': user.password,
            'phone': user.phone,
            'email': user.email,
            'id': user.id
        })

    def delete(self, request, id):
        try:
            User.objects.get(id=id).delete()
        except Exception as e:
            print(e)
            return Response({
                'code': 400,
                'msg': '删除用户失败'
            })
        return Response({
            'code': 200,
            'msg': '删除用户成功'
        })

    def put(self, request, id):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        try:
            user = User.objects.get(id=id)
            user.username = username
            user.password = password
            user.phone = phone
            user.email = email
            user.save()
        except Exception as e:
            print(e)
            return Response({
                'code': 400,
                'msg': '修改用户失败'
            })
        return Response({
            'code': 200,
            'msg': '修改用户成功'
        })


class MonthIncrementUser(APIView):
    def get(self,request):
        # 默认使用数据库连接，date_trunc_sql执行sql语句
        year_month = time.strftime("%y-%m",time.localtime(time.time()))
        select={'day':connection.ops.date_trunc_sql('day','create_time')}
        # annotate聚合函数，会根据传入的参数进行统计:根据传入的id能够统计
        count_data = User.objects.filter(create_time__contains=year_month).extra(select=select).values('day').annotate(number=Count('id'))
        data = []
        for i in count_data:
            data.append({
                'count':i['number'],
                'date':i['day']
            })
        return JsonResponse(data,safe=False)


class Userdayviews(APIView):
    def get(self,request):
        # 默认使用数据库连接，date_trunc_sql执行sql语句
        year_month = time.strftime("%y-%m",time.localtime(time.time()))
        select={'day':connection.ops.date_trunc_sql('day','last_login')}
        # annotate聚合函数，会根据传入的参数进行统计:根据传入的id能够统计
        count_data = User.objects.filter(last_login__contains=year_month).extra(select=select).values('day').annotate(number=Count('id'))
        data = []
        for i in count_data:
            data.append({
                'count':i['number'],
                'date':i['day']
            })
        return JsonResponse(data,safe=False)


# 搜索
from django.db.models import Q


class SearchView(APIView):
    def get(self, request):
        key = request.query_params.get('key')
        if key:
            user = User.objects.filter(Q(username=key) | Q(email=key) | Q(phone=key)).all()
            ser = UserSer(user, many=True)
            return Response({
                'code': 200,
                'msg': '搜索成功',
                'ser': ser.data
            })
        else:
            return Response({
                'code': 400,
                'msg': '数据不存在',
            })

































































